package com.xiaomaoguai.activiti;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 流程启动，完成下一步
 *
 * @ FileName: RuntimeServiceTest.java
 * @ Author: WeiHui-Z
 * @ Date: 2016-12-10  18:12
 * @ Version: v1.0.0
 */
public class RuntimeServiceTest {

	private static final Logger LOGGER = LoggerFactory.getLogger(ProcessDefinitionTest.class);

	private ProcessEngine processEngine;

	@Before
	public void setUp() {
		processEngine = ProcessEngines.getDefaultProcessEngine();
	}

	/**
	 * 启动流程实例--https://tkjohn.github.io/activiti-userguide/#api.services.start.processinstance
	 */
	@Test
	public void startProcessInstance() {
		Map<String, Object> variables = new HashMap<>();
		variables.put("employeeName", "Kermit");
		variables.put("numberOfDays", 4);
		variables.put("vacationMotivation", "I'm really tired!");

		// 流程定义的key
		String processDefinitionKey = "processVariables";
		//与正在执行的流程实例和执行对象相关的Service
		RuntimeService runtimeService = processEngine.getRuntimeService();
		// 使用流程定义的key启动流程实例，key对应 ACT_RE_PROCDEF 的key -->key对应*.bpmn文件中id的属性值，使用key值启动，默认是按照最新版本的流程定义启动
		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey, variables);

		LOGGER.info("当前流程实例:{},{},{}", processInstance.getBusinessKey(), processInstance.getDescription(), processInstance.getProcessInstanceId());
		LOGGER.info("当前流程实例:Number of process instances: " + runtimeService.createProcessInstanceQuery().count());
	}

	/**
	 * 查询我的任务
	 */
	@Test
	public void findMyPersonalTask() {
		String assignee = "张晓晓";
		// 与正在执行的任务管理相关的Service
		TaskService taskService = processEngine.getTaskService();
		List<Task> list = taskService.createTaskQuery(). // 创建任务查询对象
				taskAssignee(assignee)// 指定个人任务查询，指定办理人
				.list();
		if (list != null && !list.isEmpty()) {
			for (Task task : list) {
				System.out.println("任务ID:" + task.getId());
				System.out.println("任务名称:" + task.getName());
				System.out.println("任务的创建时间:" + task.getCreateTime());
				System.out.println("任务的办理人:" + task.getAssignee());
				System.out.println("流程实例ID：" + task.getProcessInstanceId());
				System.out.println("执行对象ID:" + task.getExecutionId());
				System.out.println("流程定义ID:" + task.getProcessDefinitionId());
				System.out.println("########################################################");
			}
		}
	}
}
